<template>
  <div class="container">
    <editPageNew
      ref="editPage"
      :rightBtnArr="rightBtnArr"
      :stepConfig="stepConfig"
      :creatInfo="formData"
      showTopTitle
    >
      <template slot="editPageTitle">
        <i class="el-icon-document TitleImg"></i>
        检修申请单
      </template>
      <template slot="rightBtn">
        <moreBtn
          v-if="showMoreBtn"
          :id="formData.id"
          :status="status"
          @showOperateInfo="showOperateInfo"
        ></moreBtn>
      </template>
      <div class="plan-title">
        <div v-show="!showInput" class="name">
          <span style="color: red"></span>
          <span class="titleText" :title="titleName">{{ titleName }}</span>
          <el-link
            v-show="status < 1"
            style="font-size: 20px"
            icon="el-icon-edit-outline"
            @click="editTitle"
          ></el-link>
        </div>
        <div v-show="showInput" class="name-input">
          <!-- <label>参数组名称</label> -->
          <el-input
            type="text"
            v-model="titleName"
            maxlength="64"
            show-word-limit
            @blur="loseFocus"
            placeholder="请输入名称"
            clearable
            ref="mark"
          >
            <template slot="prepend" style="color: red">名称</template>
          </el-input>
        </div>
      </div>
      <el-collapse v-model="activeNames" style="padding-right: 10px">
        <el-collapse-item name="1">
          <template slot="title">
            <span class="titleLine"></span>
            检修申请信息
          </template>
          <basic-info
            :basicInfo="formData"
            :status="status"
            @getExecuteInfo="getExecuteInfo"
            ref="basicInfo"
          ></basic-info>
        </el-collapse-item>
        <el-collapse-item name="2">
          <template slot="title">
            <span class="titleLine"></span>
            工单执行信息
          </template>
          <addPerformItem
            ref="perform"
            v-if="activeNames.includes('2') && showPerformInfo"
            :hideBtn="hidePerformBtn"
            :formData="editFormData"
            :orderType="editFormData.orderType"
            :orderStatus="editFormData.status"
            :showOnly="true"
            @changePerformData="(val) => (showPerformInfo = val)"
          ></addPerformItem>
          <el-empty v-else description="暂无执行信息"></el-empty>
        </el-collapse-item>
        <el-collapse-item name="3" v-show="showApproval">
          <template slot="title">
            <span class="titleLine"></span>
            检修批复信息
          </template>
          <overhaulApproval
            :allInfo="formData"
            :status="status"
            ref="overhaulApproval"
          ></overhaulApproval>
        </el-collapse-item>
        <el-collapse-item name="4" v-show="showStart">
          <template slot="title">
            <span class="titleLine"></span>
            检修开始信息
          </template>
          <overhaulStart
            :allInfo="formData"
            :status="status"
            ref="overhaulStart"
          ></overhaulStart>
        </el-collapse-item>
        <el-collapse-item name="5" v-show="showEnd">
          <template slot="title">
            <span class="titleLine"></span>
            检修结束信息
          </template>
          <overhaulEnd
            :allInfo="formData"
            :status="status"
            ref="overhaulEnd"
          ></overhaulEnd>
        </el-collapse-item>
        <el-collapse-item name="6" v-if="showDelay">
          <template slot="title">
            <span class="titleLine"></span>
            延时申请&批复信息
          </template>
          <delayInfo :allInfo="formData" @doApproval="doApproval"></delayInfo>
        </el-collapse-item>
      </el-collapse>
    </editPageNew>
    <dialogPublic
      :title="title"
      :show.sync="show"
      v-if="show"
      @doSubmit="delayApply"
      @doClose="() => (show = false)"
    >
      <editForm
        :formConfig="formConfig"
        ref="editForm"
        :formData="delayFormData"
      ></editForm>
    </dialogPublic>
  </div>
</template>
<script>
import {
  overhaulApplicationDetail,
  addOrUpdateOverhaulApplication,
  deleteOverhaulApplication,
  voidData,
  submitInfo,
  delaySubmit,
} from "@/api/orderManagement/overhaulApplication.js";
import { queryPageList } from "@/api/orderManagement/orderCommon.js";
import moreBtn from "./moreBtn.vue";
import basicInfo from "./basicInfo.vue";
import addPerformItem from "@/views/orderManagement/publicModule/addItem";
import overhaulApproval from "./overhaulApproval.vue";
import overhaulStart from "./overhaulStart.vue";
import overhaulEnd from "./overhaulEnd.vue";
import delayInfo from "./delayInfo.vue";
export default {
  components: {
    moreBtn,
    basicInfo,
    addPerformItem,
    overhaulApproval,
    overhaulStart,
    overhaulEnd,
    delayInfo,
  },
  data() {
    return {
      titleName: "",
      showInput: false,
      activeNames: ["1"],
      status: -1,
      pageType: "",
      formData: {},
      orderId: "",
      show: false,
      title: "",
      showPerformInfo: true,
      hidePerformBtn: true,
      editFormData: { status: "" },
      hideBtnNo: false,
      minTime: null,
      formConfig: {
        labelWidth: "150px",
        itemArr: [
          {
            label: "申请延长结束时间",
            prop: "delayTime",
            type: "datetime",
            span: 13,
            required: true,
            rules: {
              trigger: "blur",
              validator: (rule, value, callback) => {
                this.checkTime(rule, value, callback);
              },
            },
            pickerOptions: {
              disabledDate: (time) => {
                return time.getTime() < this.minTime;
              },
            },
          },
          {
            label: "申请人",
            prop: "createByName",
            type: "text",
            span: 13,
            required: true,
            disabled: true,
          },
          {
            label: "延时原因",
            prop: "delayCause",
            type: "textarea",
            span: 20,
            rows: 6,
            required: true,
          },
        ],
      },
      delayFormData: {
        applicationId: "",
        createByName: this.$store.getters.userInfo.name,
      },
    };
  },
  computed: {
    rightBtnArr() {
      let arr = [
        {
          text: "申请延时",
          icon: "el-icon-position",
          hide:
            ["details", "query", "add"].includes(this.pageType) ||
            this.status <= 1 ||
            this.status >= 4,
          content: "未授权功能",
          disabled: !this.$store.getters.isBtnAuth("approvalDelay"),
          methods: () => {
            this.approvalDelay();
          },
        },
        {
          text: "作废",
          icon: "el-icon-video-play",
          hide:
            ["details", "perform", "add"].includes(this.pageType) ||
            this.status <= 1 ||
            this.status > 2,
          content: "未授权功能",
          disabled: !this.$store.getters.isBtnAuth("invalidate"),
          methods: () => {
            this.invalidate();
          },
        },
        {
          text: "提交",
          icon: "el-icon-video-play",
          hide:
            ["details", "perform", "add"].includes(this.pageType) ||
            this.status == 1 ||
            this.status >= 4,
          content: "未授权功能",
          disabled: !this.$store.getters.isBtnAuth("submit"),
          methods: () => {
            this.submit();
          },
        },
        {
          text: "提交",
          icon: "el-icon-video-play",
          hide:
            ["details", "perform", "add"].includes(this.pageType) ||
            this.status != 1,
          content: "未授权功能",
          disabled: !this.$store.getters.isBtnAuth("reply"),
          methods: () => {
            this.submit();
          },
        },
        {
          text: "保存",
          icon: "el-icon-check",
          hide:
            ["details", "perform"].includes(this.pageType) || this.status > 0,
          content: "未授权功能",
          disabled: !this.$store.getters.isBtnAuth("save"),
          methods: () => {
            this.save();
          },
        },
        {
          text: "删除",
          icon: "el-icon-delete-solid",
          hide:
            ["perform", "details", "add"].includes(this.pageType) ||
            this.status != 0,
          content: "未授权功能",
          disabled: !this.$store.getters.isBtnAuth("delete"),
          methods: () => {
            this.deleteId();
          },
        },
      ];
      return arr;
    },
    stepConfig() {
      let obj = {};
      if (this.status != 5) {
        obj = {
          nowStep: this.status, //当前步骤，对应stepItem数组的下标，例如：0-步骤一、1-步骤二
          stepItem: ["草稿", "待批复", "已批复", "检修中", "已完成"],
        };
      } else {
        obj = {
          nowStep: this.status, //当前步骤，对应stepItem数组的下标，例如：0-步骤一、1-步骤二
          stepItem: ["已作废"],
        };
      }
      return obj;
    },
    showMoreBtn() {
      return this.pageType != "add";
    },
    //展示批复信息
    showApproval() {
      return this.status > 0;
    },
    //展示检修开始
    showStart() {
      return this.status > 1 && this.status != 5;
    },
    //展示检修结束
    showEnd() {
      return this.status > 2 && this.status != 5;
    },
    //展示延时申请
    showDelay() {
      return this.status > 1 && this.status != 5;
    },
  },
  created() {
    this.init();
  },
  watch: {
    status: {
      handler(val) {
        switch (val) {
          case 1:
            this.activeNames = ["3"];
            break;
          case 2:
            this.activeNames = ["4", "6"];
            break;
          case 3:
            this.activeNames = ["4", "5", "6"];
            break;
          case 4:
            this.activeNames = [];
            break;
          case 5:
            this.activeNames = ["1"];
            break;
          default:
            this.activeNames = ["1"];
            break;
        }
      },
    },
  },
  mounted() {
    this.$refs.mark.focus();
    let { orderId, orderCode } = this.$route.query;
    if (orderId) {
      this.$refs.basicInfo.setApplication(orderId, orderCode);
    }
  },
  methods: {
    init() {
      let { id, pageType, status, orderId, orderCode } = this.$route.query;
      this.pageType = pageType == "orderAdd" ? "add" : pageType;
      this.status = parseInt(status) || -1;
      if (this.pageType != "add") {
        this.getDetails(id);
      } else {
        this.showInput = true;
      }
    },
    //编辑标题
    editTitle() {
      this.showInput = true;
      setTimeout(() => {
        this.$refs.mark.focus();
      }, 0);
    },
    //标题输入框失去焦点
    loseFocus() {
      if (this.titleName != "") {
        this.showInput = false;
      } else {
        this.showInput = true;
        this.$message.warning("标题不能为空");
      }
    },
    showOperateInfo() {
      this.$refs.editPage.showOperate();
    },
    //打开延时申请弹框
    approvalDelay() {
      this.title = "延时申请";
      this.delayFormData.applicationId = this.formData.id;
      this.minTime = new Date(
        `${this.formData.applicationCheck.endTime.split(" ")[0]} 00:00`
      ).getTime();
      this.show = true;
    },
    getExecuteInfo(data) {
      this.editFormData = data;
    },
    //完成批复
    doApproval() {
      this.getDetails(this.formData.id);
    },
    //获取检修申请详情
    getDetails(id) {
      overhaulApplicationDetail({ id: id }).then((res) => {
        if (res.code == 200) {
          this.formData = res.data;
          this.status = this.formData.status;
          this.titleName = this.formData.title;
          //this.getOrderId(this.formData.orderCode);
          this.editFormData = {
            id: this.formData.orderId,
            orderType: this.formData.orderCategory,
          };
        }
      });
    },
    //获取工单id
    getOrderId(code) {
      queryPageList({ code: code }).then((res) => {
        this.editFormData = res.data.list[0] || {};
      });
    },
    //删除维保计划
    deleteId() {
      this.$confirm("确定要删除该条数据吗", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          deleteOverhaulApplication({ id: this.formData.id }).then((res) => {
            if (res.code === 200) {
              this.$message.success(res.description);
              this.$utils.addOperateLog(this.formData.id, "删除了检修申请单");
              this.updateListData();
              this.$refs.editPage.closePage();
            }
          });
        })
        .catch((e) => {});
    },
    //保存检修申请单
    async save() {
      let params = await this.$refs.basicInfo.getBasicInfo();
      params.title = this.titleName;
      if (this.titleName == "") {
        this.loseFocus();
      } else {
        if (!params.equipmentList || params.equipmentList.length == 0) {
          this.$confirm("您未填写检修设备，是否继续保存？", "", {
            confirmButtonText: "继续",
            cancelButtonText: "再想想",
            distinguishCancelAndClose: true,
            type: "warning",
          })
            .then(async () => {
              let res = await addOrUpdateOverhaulApplication(params);
              if (res.code == 200) {
                this.$message.success(res.description);
                this.updateListData();
                await this.$refs.basicInfo.uploadFile(res.data);
                if (this.pageType == "add") {
                  this.$utils.addOperateLog(res.data, "新建了检修申请单");
                  let obj = {
                    id: res.data,
                    pageType: "edit",
                  };
                  this.$router.push({
                    query: obj,
                  });
                } else {
                  this.$utils.addOperateLog(
                    this.formData.id,
                    "修改了检修申请单"
                  );
                  this.getDetails(this.formData.id);
                }
              }
            })
            .catch((error) => {});
        } else {
          let res = await addOrUpdateOverhaulApplication(params);
          if (res.code == 200) {
            this.$message.success(res.description);
            this.updateListData();
            await this.$refs.basicInfo.uploadFile(res.data);
            if (this.pageType == "add") {
              this.$utils.addOperateLog(res.data, "新建了检修申请单");
              let obj = {
                id: res.data,
                pageType: "edit",
              };
              this.$router.push({
                query: obj,
              });
            } else {
              this.$utils.addOperateLog(this.formData.id, "修改了检修申请单");
              this.getDetails(this.formData.id);
            }
          }
        }
      }
    },
    //提交
    async submit() {
      let params = {};
      params = await this.$refs.basicInfo.getBasicInfo();
      params.title = this.titleName;
      let operateContent = "检修申请信息";
      if (this.status == 1) {
        params.applicationCheck = await this.$refs.overhaulApproval.getApprovalInfo();
        operateContent = "检修批复信息";
      } else if (this.status == 2) {
        params.applicationTime = await this.$refs.overhaulStart.getFactStartData();
        operateContent = "检修开始信息";
      } else if (this.status == 3) {
        params.applicationTime = await this.$refs.overhaulEnd.getFactEndData();
        operateContent = "检修结束信息";
      }
      if (this.status > 1 && !this.isDelayNoApproval()) {
        this.$message.warning("还有延时申请未批复，无法提交");
      } else if (this.status == 0) {
        if (!params.equipmentList || params.equipmentList.length == 0) {
          this.$confirm("您未填写检修设备，是否继续提交？", "", {
            confirmButtonText: "继续",
            cancelButtonText: "再想想",
            distinguishCancelAndClose: true,
            type: "warning",
          })
            .then(() => {
              submitInfo(params).then((res) => {
                this.$message.success(res.description);
                this.$utils.addOperateLog(
                  this.formData.id,
                  `提交了${operateContent}`
                );
                this.getDetails(this.formData.id);
              });
            })
            .catch((action) => {});
        } else {
          submitInfo(params).then((res) => {
            this.$message.success(res.description);
            this.$utils.addOperateLog(
              this.formData.id,
              `提交了${operateContent}`
            );
            this.getDetails(this.formData.id);
          });
        }
      } else {
        submitInfo(params).then((res) => {
          this.$message.success(res.description);
          if (params.applicationCheck.result) {
            this.$utils.addOperateLog(this.formData.id, `同意检修申请`);
          } else {
            this.$utils.addOperateLog(
              this.formData.id,
              `不同意检修申请\n${params.applicationCheck.opinion}`
            );
          }
          this.getDetails(this.formData.id);
        });
      }
    },
    //申请延时
    async delayApply() {
      let formData = await this.$refs.editForm.getFormData();
      delaySubmit(formData).then((res) => {
        if (res.code == 200) {
          this.$message.success(res.description);
          this.$utils.addOperateLog(this.formData.id, "申请延时了检修申请单");
          this.show = false;
          this.getDetails(this.formData.id);
        }
      });
    },
    //作废
    invalidate() {
      if (this.isDelayNoApproval()) {
        this.$confirm("确定要作废该条数据吗", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            voidData({ id: this.formData.id }).then((res) => {
              if (res.code == 200) {
                this.$message.success(res.description);
                this.$utils.addOperateLog(this.formData.id, "作废了检修申请单");
                this.updateListData();
                this.getDetails(this.formData.id);
              }
            });
          })
          .catch((e) => {});
      } else {
        this.$message.warning("还有延时申请未批复，无法作废");
      }
    },
    //是否有延时申请未批复
    isDelayNoApproval() {
      if (this.formData.applicationDelayList.length == 0) {
        return true;
      } else {
        return this.formData.applicationDelayList.every((item) => {
          return item.status != 0;
        });
      }
    },
    //校验申请时间
    checkTime(rule, val, callback) {
      let maxTime = new Date(this.formData.applicationCheck.endTime).getTime();
      let endTime = new Date(val).getTime();
      let message = `请选择${this.formData.applicationCheck.endTime}之后的时间`;
      if (endTime < maxTime) {
        //debugger
        return callback(new Error(message));
      } else {
        callback();
      }
    },
    updateListData() {
      /* 通过localStorage来实现浏览器不同窗口之间的通信 */
      let num = Math.floor(Math.random() * 1000) + 1; //产生随机数，保证每次的值都不一样
      localStorage.setItem("update", num); //设置localStorage里面的值，保证每次都会触发storage事件
    },
  },
};
</script>
<style lang="less" scoped>
.container {
  height: 100%;
  width: 100%;
  overflow: hidden;
  background-color: #ffffff;
  .TitleImg {
    margin-right: 2px;
    font-size: 22px;
  }
  .plan-title {
    height: 40px;
    margin: 0 0 10px 0;
    .name {
      font-size: 18px;
      padding: 0 10px;
      height: 40px;
      font-weight: bold;
      line-height: 40px;
      text-align: left;
      padding: 0 10px;
    }
    .name-input {
      width: 600px;
      height: 40px;
      line-height: 40px;
    }
    .titleText {
      display: inline-block;
      height: 30px;
      max-width: 800px;
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
      margin-right: 5px;
    }
    .el-link {
      margin-bottom: 5px;
    }
  }
}
</style>
